<template>
  <!-- 后台服务的权限管理-->
  <div class="hs-panel hs-bg-card">
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px" placeholder="姓名或账户" v-model="listQuery.name"> </el-input>
      <el-button type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button type="primary" v-if="serviceManager_btn_add" style="margin-left: 10px" @click="handleCreate"  icon="el-icon-plus">添加</el-button>
    </div>
    <el-table :key='tableKey' :data="list"
              v-loading.body="listLoading"
              border fit highlight-current-row
              style="width: 100%; margin: 10px 0">
      <el-table-column type="index" width="50" label="序号"> </el-table-column>
      <el-table-column width="150" label="服务编码" prop="code">
      </el-table-column>
      <el-table-column width="ont-awesome-webpack150" label="服务密钥" prop="secret">
      </el-table-column>
      <el-table-column width="150" label="服务名" prop="name">
      </el-table-column>
      <!-- <el-table-column width="200px" align="center" label="是否锁定" prop="locked" >
      </el-table-column> -->
      <el-table-column width="160" align="center" label="描述" prop="description">
      </el-table-column>
      <el-table-column width="160" align="center" label="创建时间" prop="crtTime">
      </el-table-column>
      <el-table-column width="80" align="center" label="创建人ID" prop="crtUser">
      </el-table-column>
      <el-table-column width="90" align="center" label="创建人" prop="crtName">
      </el-table-column>
      <el-table-column width="120" align="center" label="创建主机" prop="crtHost">
      </el-table-column>
      <el-table-column width="160" align="center" label="更新时间" prop="updTime">
      </el-table-column>
      <el-table-column width="80" align="center" label="更新人ID" prop="updUser">
      </el-table-column>
      <el-table-column width="100" align="center" label="更新人" prop="updName">
      </el-table-column>
      <el-table-column width="120" align="center" label="更新主机" prop="updHost">
      </el-table-column>
      <el-table-column fixed="right" align="center" label="操作" width="150">
        <template slot-scope="scope">
        <el-button v-if="serviceManager_btn_clientManager" size="medium"  type="text" @click="handleAuthClient(scope.row)">授权
        </el-button>
        <el-button v-if="serviceManager_btn_edit" size="small" type="success" icon="el-icon-edit" circle @click="handleUpdate(scope.row)"> </el-button>
        <el-button v-if="serviceManager_btn_del" size="small" type="danger" icon="el-icon-delete" circle @click="handleDelete(scope.row)"> </el-button>
      </template> </el-table-column>
    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="服务编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入服务编码"></el-input>
        </el-form-item>
        <el-form-item label="服务密钥" prop="secret">
          <el-input v-model="form.secret" placeholder="请输入服务密钥"></el-input>
        </el-form-item>
        <el-form-item label="服务名" prop="name">
          <el-input v-model="form.name" placeholder="请输入服务名"></el-input>
        </el-form-item>
        <!-- <el-form-item label="是否锁定" prop="locked">
      <el-input v-model="form.locked" placeholder="请输入是否锁定"></el-input>
    </el-form-item> -->
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入描述"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('form')">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="create('form')">确 定</el-button>
        <el-button v-else type="primary" @click="update('form')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="dialogClientName" :visible.sync="dialogClientVisible">
      <el-form label-width="140px">
        <el-form-item label="当前服务:">
          <el-tag > {{selectedService.name}}</el-tag>
        </el-form-item>

        <el-form-item label="允许去访问服务:">
          <el-select v-model="clients" multiple filterable remote
                     placeholder="请输入服务关键词"
                     :remote-method="remoteMethod" :loading="loading">
            <el-option v-for="item in items" :key="item.id" :label="item.name" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-if="serviceManager_btn_clientManager" @click="onSubmit">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { page, addObj, getObj, delObj, putObj, getClients, modifyClients } from 'api/auth/service'
import { mapGetters } from 'vuex'
export default {
  name: 'client',
  components: {},
  data () {
    return {
      form: {
        code: undefined,
        secret: undefined,
        name: undefined,
        description: undefined
      },
      rules: {
        code: [
          { required: true, message: '请输入服务编码', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        secret: [
          { required: true, message: '请输入服务密钥', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入服务名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入描述', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ]
      },
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: undefined
      },
      selectedService: undefined,
      items: [],
      clients: [],
      loading: false,
      dialogFormVisible: false,
      dialogClientName: '授权服务',
      dialogClientVisible: false,
      dialogStatus: '',
      serviceManager_btn_edit: false,
      serviceManager_btn_del: false,
      serviceManager_btn_add: false,
      serviceManager_btn_clientManager: false, // 授权
      textMap: {
        update: '编辑',
        create: '创建'
      },
      tableKey: 0
    }
  },
  created () {
    this.getList()
    this.serviceManager_btn_edit = this.elements['serviceManager:btn_edit']
    this.serviceManager_btn_del = this.elements['serviceManager:btn_del']
    this.serviceManager_btn_add = this.elements['serviceManager:btn_add']
    this.serviceManager_btn_clientManager = this.elements['serviceManager:btn_clientManager']
  },
  computed: {
    ...mapGetters({
      elements: 'userElements'
    })
  },
  methods: {
    getList () {
      this.listLoading = true
      page(this.listQuery).then(response => {
        this.list = response.data.rows
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter () {
      this.getList()
    },
    handleSizeChange (val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange (val) {
      this.listQuery.page = val
      this.getList()
    },
    handleCreate () {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    handleUpdate (row) {
      getObj(row.id).then(response => {
        this.form = response.data
        this.dialogFormVisible = true
        this.dialogStatus = 'update'
      })
    },
    handleDelete (row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delObj(row.id).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
        })
      })
    },
    handleAuthClient (val) {
      this.selectedService = val
      console.log('handleDataCurrentChange: ' + val.id)
      this.dialogClientVisible = true
      this.initClients() // 获取客户端
    },
    create (formName) {
      const set = this.$refs
      set[formName].validate(valid => {
        if (valid) {
          addObj(this.form).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        } else {
          return false
        }
      })
    },
    cancel (formName) {
      this.dialogFormVisible = false
      const set = this.$refs
      set[formName].resetFields()
    },
    update (formName) {
      const set = this.$refs
      set[formName].validate(valid => {
        if (valid) {
          this.dialogFormVisible = false
          this.form.password = undefined
          putObj(this.form.id, this.form).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        } else {
          return false
        }
      })
    },
    resetTemp () {
      this.form = {
        username: undefined,
        name: undefined,
        sex: '男',
        password: undefined,
        description: undefined
      }
    },
    // -- 服务授权
    remoteMethod (query) {
      if (query !== '') {
        this.loading = true
        page({ name: query }).then(response => {
          this.items = response.data.rows
          this.total = response.data.total
          this.loading = false
        })
      } else {
        this.items = []
      }
    },
    onSubmit () {
      const vals = {}
      if (this.clients.length > 0) vals.clients = this.clients.join()
      modifyClients(this.selectedService.id, vals).then(() => {
        this.dialogClientVisible = false
        this.$notify({
          title: '成功',
          message: '保存成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    initClients () {
      if (!this.selectedService) {
        return
      }
      getClients(this.selectedService.id).then(response => {
        this.items = response.data
        const leas = []
        for (let i = 0; i < response.data.length; i++) {
          leas.push(response.data[i].id)
        }
        this.clients = leas
      })
    }
  }
}
</script>
